package com.example.myapplication

import android.os.Bundle
import android.widget.Toolbar
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity2 : AppCompatActivity() {
    private lateinit var bottomNV: BottomNavigationView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        bottomNV = findViewById(R.id.bottom_navigation)
        bottomNV.selectedItemId = R.id.info
        if (savedInstanceState == null) {
            replaceFragement(Person_information.newInstance())
        }
        bottomNV.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.game -> {
                    val fragment = ThirdFragment.newInstance()
                    setTargetFragment(fragment)
                    replaceFragement(fragment)
                    true
                }
                R.id.info -> {
                    val fragment = Person_information.newInstance()
                    replaceFragement(fragment)
                    true
                }
                R.id.game2 -> {
                    val fragment = FourthFragment.newInstance()
                    setTargetFragment(fragment)
                    replaceFragement(fragment)
                    true
                }
                else -> false

            }
        }}
        private fun replaceFragement(fragment: Fragment) {
            val curetnFragment = supportFragmentManager.findFragmentById(R.id.frameLayout)
            if (curetnFragment != null && curetnFragment::class == fragment::class) return
            supportFragmentManager.beginTransaction()
                .replace(R.id.frameLayout, fragment)
                .addToBackStack(null)
                .commit()
        }
        private fun setTargetFragment(fragment: Fragment) {
             val currentFragment = supportFragmentManager.findFragmentById(R.id.frameLayout)
            currentFragment?.let{
                fragment.setTargetFragment(it, REQUEST_CODE_GAME)
            }
        }
        companion object {
            const val REQUEST_CODE_GAME = 2
        }



}